import React, { Component } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Button, notification, Select, Radio, Row, Col } from 'antd';
import Imgviewer from '@/components/ImgViewer';
import { DropDownSelect } from '@/components/DropDownSelect';
import { DividerItem } from '@/components/DividerItem';
import { MyButton } from '@/styled/form';
import { MyIcon } from '@/components/MyIcon';
import { inject_unount } from '@/utils/middleware';

const Option = Select.Option;

@connect(({ person, upload }) => ({
	dict: person.dict,
	img: upload.imgValue,
	roles: person.roles,
	roomList: person.roomList || []
}))
@inject_unount
class FormItem extends Component<any> {
	state = {
		pwd: 0, //密码的
		isCheck: 0,// 判断最大的
		isPhoto: 0,// 判断是否上传图片
		confirmDirty: false,
		autoCompleteResult: [],
		isNew: true,
		option: []
	};

	componentDidMount() {
		const { data, form, dispatch } = this.props;
		//获取消控室列表
		dispatch({
			type: 'person/queryFireRoomList',
		})
		dispatch({
			type: 'person/init',
			payload: {
				dict: { keyList: ['user.position'] },
				url: data ? data.photo : null
			}
		});

		if (data) {
			const {
				id,
				photo,
				userInfomation = {},
				loginName,
				realName,
				loginPwd,
				mobile,
				position,

			} = data;
			const { isDuty, idCardNo, isHasCard, fireRoomIds, certificate, } = userInfomation
			dispatch({ type: 'upload/setImgValue', payload: { url: photo } });
			form.setFieldsValue({
				position,
				mobile,
				realName,
				loginName,
				isDuty,
				idCardNo,
				fireRoomIds,
				// ...userInfomation
			});
			//dom已经生成，可以设置values
			this.setState({
				pwd: `${loginPwd}`,
				isCheck: isDuty,
				isPhoto: isHasCard
			}, () => {
				form.setFieldsValue({
					isHasCard,
					certificate,
				})
			})
		}
	}

	handleSubmit = (e) => {
		e.preventDefault();

		const { form, data = {}, dispatch, img } = this.props; //img 服务器返回的img.url
		let { image = 'image' } = data.userInfomation || { image: 'image' }

		form.validateFields((err, values) => {
			if (this.state.isPhoto === 0) {
				image = null
			}
			if (!err) {
				data.id
					? dispatch({
						type: 'person/update',
						payload: {
							id: data.id,
							...values,
							information: {
								...values,
								image: img.url ? img.url : image //当没有修改图片，回显以前的
							}
						}
					})
					: dispatch({
						type: 'person/create',
						payload: {
							...values,
							information: {
								...values,
								image: img.url ? img.url : null // 没有选择图片给null
							}
						}
					});
			} else {
				notification['error']({
					message: `${data.id ? '修改' : '创建'}失败`,
					description: '字段验证不通过'
				});
			}
		});
	};

	handleConfirmBlur = (e) => {
		const value = e.target.value;
		this.setState({ confirmDirty: this.state.confirmDirty || !!value });
	};

	compareToFirstPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && value !== form.getFieldValue('loginPwd')) {
			callback('两次输入的密码不一致');
		} else {
			callback();
		}
	};

	validateToNextPassword = (rule, value, callback) => {
		const form = this.props.form;
		if (value && this.state.confirmDirty) {
			form.validateFields(['confirm'], { force: true });
		}
		callback();
	};

	uploadImage(e) {
		e.persist();
		const { dispatch } = this.props;

		const file = e.target.files[0];
		dispatch({ type: 'upload/uploadImg', payload: file });
	}



	render() {
		const { form, data = {}, dict = {}, img, roomList } = this.props;
		const { userInfomation = {} } = data
		const { getFieldDecorator, getFieldsValue, getFieldValue } = form;
		const { isHasCard, isDuty } = getFieldsValue()
		const formItemLayout = {
			labelCol: {
				xs: { span: 12 },
				sm: { span: 6 },
			},
			wrapperCol: {
				xs: { span: 6 },
				sm: { span: 14 },
			},
		};
		const ButtonList = () => (
			<Form.Item>
				<Button style={{ marginLeft: 20 }} onClick={() => {
					window.history.back()
				}}>取消</Button>
				<Button type="primary"
					htmlType="submit"
					style={{ marginLeft: 20 }}
					onClick={(e: any) => {
						this.handleSubmit(e)
					}}
				>保存</Button>
			</Form.Item>
		)
		const iconName = data.id ? 'edit' : 'plus'
		const title = data.id ? '编辑' : '新增人员'
		const Info = DividerItem(iconName, title);
		return (

			<Form>
				<Info />
				<Row>
					<Col span={12}>
						<Form.Item {...formItemLayout} label="用户名">
							{getFieldDecorator('loginName', {
								rules: [
									{
										required: true,
										message: '请输入登录名'
									}
								]
							})(<Input placeholder="请输入用户登录名" disabled={!!data.id} />)}
						</Form.Item>
						<Form.Item {...formItemLayout} label="真实姓名">
							{getFieldDecorator('realName', {
								rules: [{ required: true, message: '请输入真实姓名', whitespace: true }]
							})(<Input placeholder="请输入真实姓名" />)}
						</Form.Item>
						{
							!data.id &&
							<div>
								<Form.Item {...formItemLayout} label="密码">
									{getFieldDecorator('loginPwd', {
										rules: [
											{
												required: true,
												message: '请输入密码'
											},
											{
												validator: this.validateToNextPassword
											}
										]
									})(<Input.Password placeholder="请输入密码" type="password"
									/>)}
								</Form.Item>

								{
									getFieldValue('loginPwd') !== this.state.pwd &&
									<Form.Item {...formItemLayout} label="确认密码">
										{
											getFieldDecorator('confirm', {
												rules: [
													{
														required: true,
														message: '请再次输入您的密码'
													},
													{
														validator: this.compareToFirstPassword
													}
												]
											}
											)(<Input.Password placeholder="再次输入密码验证" type="password" onBlur={this.handleConfirmBlur} />)

										}
									</Form.Item>
								}
							</div>
						}

						<Form.Item {...formItemLayout} label="手机号">
							{getFieldDecorator('mobile', {
								rules: [{ required: true, message: '请输入手机号' }]
							})(<Input placeholder="请输入手机号" />)}
						</Form.Item>

						<Form.Item {...formItemLayout} label="岗位">
							{getFieldDecorator('position', {
								rules: [{ required: true, message: '请输入用户岗位', whitespace: true }]
							})(DropDownSelect(dict, 'user.position'))}
						</Form.Item>

						<Row style={{ width: '60%', marginLeft: 200 }}>
							<Col span={12}>
								<Form.Item {...formItemLayout} label="值班人员">
									{getFieldDecorator('isDuty', {
										rules: [{ required: true, message: '请选择值班人员' }]
									})(
										<Radio.Group onChange={(e) => this.setState({ isCheck: e.target.value })}>
											<Radio value={1}>是</Radio>
											<Radio value={0}>否</Radio>
										</Radio.Group>
									)}
								</Form.Item>
							</Col>
							{/* 显示和隐藏 开始*/}
							<Col span={12} style={{ display: `${(isDuty === 1) ? 'block' : 'none'}` }}>
								{
									this.state.isCheck === 1 &&

									<Form.Item style={{ marginLeft: -50 }} {...formItemLayout} label="持证上岗">
										{getFieldDecorator('isHasCard', {
											rules: [{ required: true, message: '请选择是否持证' }]
										})(
											<Radio.Group onChange={(e) => this.setState({ isPhoto: +e.target.value })}>
												<Radio value={1}>是</Radio>
												<Radio value={0}>否</Radio>
											</Radio.Group>
										)}
									</Form.Item>

								}

							</Col>
						</Row>
						{
							(this.state.isCheck === 1 && this.state.isPhoto === 1) &&
							<Row style={{ width: '58%', marginLeft: 200, display: `${(isHasCard === 1 && isDuty === 1) ? 'block' : 'none'}` }}>
								<Col span={12}>
									<Form.Item  {...formItemLayout} label="证书编号">
										{getFieldDecorator('certificate', {
											rules: [{ required: true, message: '请输入证书编号' }]
										})(<Input placeholder="请输入证书编号" />)}
									</Form.Item>
								</Col>
								<Col span={12}>
									<Form.Item style={{ marginLeft: -30 }} {...formItemLayout} label="证书照片" required>
										{
											getFieldDecorator('image', {
												// rules: [{ required: true }]
											})(
												<input
													style={{ opacity: 0, width: 120, zIndex: 10, position: 'absolute', cursor: 'pointer' }}
													onChange={(e) => {
														this.uploadImage(e);
													}}
													type="file"
													accept="image/*"
												/>
											)
										}

										<MyButton style={{ marginTop: -50 }}> <MyIcon icon="upload" />上传图片</MyButton>
										<div style={{ display: 'inline-block', marginLeft: 10 }}>
											<Imgviewer hasText="查看头像" missText="暂无头像" url={img.url || userInfomation.image} />
										</div>
										{/* {img.message === 'success' ? '上传成功' : img.message === 'fail' ? '上传失败' : ''} */}
									</Form.Item>
								</Col>
							</Row>
						}
						{/* 显示和隐藏 结束*/}

						<Form.Item label="所属消控室" {...formItemLayout}>
							{getFieldDecorator('fireRoomIds', {
								rules: [{ required: true, type: 'array', message: '请选择所属消控室' }]
							})(
								<Select mode="multiple" placeholder="请选择所属消控室">
									{roomList.map((item) => (
										<Option value={item.id} key={item.id}>
											{item.name}
										</Option>
									))}
								</Select>
							)}
						</Form.Item>

						<Form.Item {...formItemLayout} label="身份证号">
							{getFieldDecorator('idCardNo', {
								rules: [{ required: false, message: '请输入身份证号' }]
							})(<Input placeholder="请输入身份证号" />)}
						</Form.Item>
					</Col>
					<Col span={12}></Col>
				</Row>
				<Row><ButtonList /></Row>
			</Form>
		);
	}
}

const FormList = Form.create()(FormItem);
export default FormList;
